#include "metadata.h"

/* Metadata constructor for the first meta data of repository file */

Metadata::Metadata ( char *filename, char *version )
{
	/* Learn Delta's size ( which actually is the file's size
 	 *because this is the first metadata.
	 */

	fstream targetFile ( filename, ios::in );
	targetFile.seekg ( 0, ios::end );
	deltaSize = targetFile.tellg();

	/* Store file's version */

	if ( version == NULL )
		sprintf ( this->version, "%s", "1.0" );
	else
	{
		strcpy ( this->version, version );
	}

	/* Get creation Date */

	GetDate ( creationDate );
	
	/* Get version's comments */

	cout << "Please, leave a comment for the" << filename << "'s version: ";
	cin.getline ( this->comments, 100 );

	this->tag = development;
}
void Metadata::PreviousMetaData ( Metadata &metadata )
{
    /* Get date of check in */

    GetDate ( this->creationDate );

    /* Get version's tag */
    this->tag = development;

    /* Get version's comment */

    cout << "Please, leave a comment for the version: ";
    cin.getline ( this->comments, 100 );

    /* Get delta size */

    ifstream stream;
    stream.open ( "delta", ios::in );
    stream.seekg( 0, ios::end );
    this->deltaSize = stream.tellg();
    stream.close();

    /* Compute new version */

    char *pointer = &metadata.version[strlen(metadata.version) - 1];

    while ( *pointer != '.' )
        pointer--;

    int versionNo = atoi ( ++pointer );
    *pointer = '\0';
    versionNo++;
    sprintf( this->version, "%s%d", metadata.version, versionNo );
}
void Metadata::GetDate ( char *string )
{
	time_t tim = time ( NULL );
 	tm *now = localtime ( &tim );
        sprintf ( string, "%d/%02d/%02d", now->tm_year+1900, now->tm_mon+1, now->tm_mday );
}
ostream & operator << ( ostream &stream, Metadata metadata )
{
	stream << metadata.version << endl;		
	stream <<  metadata.creationDate << endl;	
	stream <<  metadata.comments << endl;
	stream <<  metadata.deltaSize << endl;		
	stream <<  metadata.tag << endl;

	return stream;
}
istream & operator >> ( istream &stream, Metadata &metadata )
{
	stream >> metadata.version;
	stream >>  metadata.creationDate;

        char buffer[100];

        stream >> buffer[0];
        stream.getline ( &buffer[1], 100 );
        strncpy ( metadata.comments, buffer, 100 );

	stream >>  metadata.deltaSize;

        int tag;
        stream >>  tag;
        tag == 0 ? metadata.tag = development : metadata.tag = stable;

        return stream;
}
void Metadata::Version(char* version)
{
    strcpy ( version, this->version );
}

void Metadata::Date(char* date)
{
    strcpy ( date, this->creationDate );
}